<?php
class ArticleController extends MyAdminController
{
	const PAGE_SIZE = 50;

	public function init()
	{
		parent::init();
	}

	public function actionIndex()
	{
		$page = intval(Yii::app()->request->getParam('pageNum')) - 1;
		$keyword = Yii::app()->request->getParam('keyword');
		$category_id = intval(Yii::app()->request->getParam('category_id'));

		// 查库
		$CDbCriteria = new CDbCriteria;
		$CDbCriteria->order = "create_time DESC";
		$CDbCriteria->condition = 1;
		if($keyword)
		{
			$CDbCriteria->condition .= " AND (title LIKE '%{$keyword}%' OR content LIKE '%{$keyword}%') ";
		}
		if($category_id)
		{
			$CDbCriteria->condition .= " AND id in (select article_id from article_category_relation where category_id={$category_id}) ";
		}

		// 分页
		$count = Article::model()->count($CDbCriteria);
		$pages = new CPagination($count);
		$pages->pageSize = self::PAGE_SIZE;
		$pages->currentPage = $page;
		$pages->applyLimit($CDbCriteria);

		$rows = Article::model()->findAll($CDbCriteria);

		$CDbCriteria = new CDbCriteria;
		$CDbCriteria->order = "id DESC";
		$CDbCriteria->condition = "model_type = 0";
		$categorys = Article_category::model()->findAll($CDbCriteria);

		// 显示
		$data = array();
		$data['rows'] = $rows;
		$data['pages'] = $pages;
		$data['categorys'] = $categorys;
		$this->display('index', $data);
	}

	/**
	 * 添加文章
	 */
	public function actionAdd()
	{
		$url_key = str_replace(' ','',Yii::app()->request->getParam('url'));
		$categorys = Yii::app()->request->getParam('category');
		$title = Yii::app()->request->getParam('title');
		$content = trim(Yii::app()->request->getParam('content'));
		$en_title = Yii::app()->request->getParam('en_title');
		$en_content = trim(Yii::app()->request->getParam('en_content'));
		$color = trim(Yii::app()->request->getParam('color'));
		$tags = trim(Yii::app()->request->getParam('tags'));

		//如果提交内容
		if($title)
		{
			if(!$url_key)
			{
				$this->alert_error('URL地址不能为空');
			}
			$cond = new CDbCriteria();
			$cond->condition = "url_key=:url";
			$cond->params = array(":url"=>$url_key);
			if(Article::model()->exists($cond))
			{
				$this->alert_error('URL地址不能重复');
			}
			if(empty($categorys))
			{
				$this->alert_error('请选择一个分类');
			}
			$article = new Article();
			$article->url_key = $url_key;
			$article->title = $title;
			$article->en_title = $en_title;
			$article->content = $content;
			$article->en_content = $en_content;
			$article->create_time = date('Y-m-d H:i:s');
			$article->update_time = date('Y-m-d H:i:s');
			$article->is_recommend = 0;
			$article->color = $color;
			$article->visit = 0;
			$article->cached = 0;
			if($article->save())
			{
				foreach ($categorys as $category_id)
				{
					$category = Article_category::model()->findByPk($category_id);
					if(!$category)
					{
						$this->alert_error('分类'.$category_id.'不存在');
					}
					if($category->model_type == 1)
					{
						$this->alert_error('分类模型为链接模型，不能添加文章');
					}
					else 
					{
						Article_category_relation::model()->newrecord($article->id,$category_id);
					}
				}
				//tag
				$tags = str_replace('，',",",$tags);
				$tag_arr = explode(',',$tags);
				foreach ($tag_arr as $k=>$v)
				{
					$tag_arr[$k] = trim($v);
					if(!$tag_arr[$k])
					{
						unset($tag_arr[$k]);
					}
				}
				$tag_arr = array_unique($tag_arr);
				foreach ($tag_arr as $k=>$v)
				{
					$this->addtag($article->id,$tag_arr[$k]);
				}
				//通知抓取feed，通知google
				//http://blogsearch.google.com/ping?name=%E6%9C%A8%E5%81%B6%E7%9A%84%E7%BE%8E%E8%B4%AD%E6%8C%87%E5%8D%97&url=http%3A%2F%2Fixuepin.us&changesURL=http%3A%2F%2Fixuepin.us%2Ffeed
				//
				MyController::get_url('http://blogsearch.google.com/ping?name=%E6%9C%A8%E5%81%B6%E7%9A%84%E7%BE%8E%E8%B4%AD%E6%8C%87%E5%8D%97&url=http%3A%2F%2Fixuepin.us&changesURL=http%3A%2F%2Fixuepin.us%2Ffeed');
				//通知
				$result = MyController::get_url('http://www.feedburner.com/fb/a/pingSubmit?bloglink=http%3A%2F%2Fixuepin.us');
				$time = 0;
				while ($time <3 )
				{
					$result = MyController::get_url('http://www.feedburner.com/fb/a/pingSubmit?bloglink=http%3A%2F%2Fixuepin.us');
					$time ++;
					if(strpos($result['content'], 'Successfully pinged'))
					{
						$this->alert_ok('发布成功，并且已经通知了feedburner');
					}
				}
				$this->alert_ok('feedburner 可能抽风了，请手动通知');
			}
			else
			{
				$this->alert_error();
			}
		}
		else
		{
			$data = array();
			$data['tags'] = Tag::model()->findAll('1 order by used_times desc limit 20');
			$data['categorys'] = Article_category::model()->findAll('model_type=0');
			$this->display('add', $data);
		}
	}

	/**
	 * 修改文章
	 */
	public function actionEdit()
	{
		$id = intval(Yii::app()->request->getParam('id'));
		$url_key = str_replace(' ','',Yii::app()->request->getParam('url'));
		$categorys = Yii::app()->request->getParam('category');
		$title = Yii::app()->request->getParam('title');
		$content = trim(Yii::app()->request->getParam('content'));
		$en_title = Yii::app()->request->getParam('en_title');
		$en_content = trim(Yii::app()->request->getParam('en_content'));
		$color = trim(Yii::app()->request->getParam('color'));
		$tags = trim(Yii::app()->request->getParam('tags'));

		if(!$id)
		{
			$this->alert_error('ID不能为空');
		}

		$article = Article::model()->findByPk($id);
		if(!$article)
		{
			$this->alert_error('文章不存在');
		}

		//如果提交内容
		if($title)
		{
			if(!$url_key)
			{
				$this->alert_error('URL地址不能为空');
			}
			$cond = new CDbCriteria();
			$cond->condition = "url_key=:url and id<>{$id}";
			$cond->params = array(":url"=>$url_key);
			if(Article::model()->exists($cond))
			{
				$this->alert_error('URL地址不能重复');
			}
			if(empty($categorys))
			{
				$this->alert_error('请选择一个分类');
			}
			$article->url_key = $url_key;
			$article->title = $title;
			$article->en_title = $en_title;
			$article->content = $content;
			$article->en_content = $en_content;
			$article->update_time = date('Y-m-d H:i:s');
			$article->cached = 0;
			$article->color = $color;
			if($article->save())
			{
				Article_category_relation::model()->deleteAll("article_id=$id");
				foreach ($categorys as $category_id)
				{
					$category = Article_category::model()->findByPk($category_id);
					if(!$category)
					{
						$this->alert_error('分类'.$category_id.'不存在');
					}
					if($category->model_type == 1)
					{
						$this->alert_error('分类模型为链接模型，不能添加文章');
					}
					else 
					{
						Article_category_relation::model()->newrecord($article->id,$category_id);
					}
				}
				//tag
				$tags = str_replace('，',",",$tags);
				$tag_arr = explode(',',$tags);
				foreach ($tag_arr as $k=>$v)
				{
					$tag_arr[$k] = trim($v);
					if(!$tag_arr[$k])
					{
						unset($tag_arr[$k]);
					}
				}
				$tag_arr = array_unique($tag_arr);
				$exist_relations = Article_tag_relation::model()->findAll('article_id='.$article->id);
				foreach ($exist_relations as $row)
				{
					if(!in_array($row->tag->tag, $tag_arr))
					{
						$row->tag->used_times --;
						$row->tag->save();
						$row->delete();
					}
					else 
					{
						unset($tag_arr[array_search($row->tag->tag, $tag_arr)]);
					}
				}
				foreach ($tag_arr as $v)
				{
					$this->addtag($article->id,$v);
				}
				$this->alert_ok('操作成功');
			}
			else
			{
				$this->alert_error();
			}
		}
		else
		{
			$categorys = Article_category::model()->findAll('model_type=0');
			$selected_category = array();
			foreach ($article->relation as $r)
			{
				$selected_category[] = $r->category_id;
			}
			$data = array();
			$data['article'] = $article;
			$data['categorys'] = $categorys;
			$data['tags'] = Tag::model()->findAll('1 order by used_times desc limit 20');
			$data['selected_category'] = $selected_category;
			$this->display('edit', $data);
		}
	}
	
	public function actionSavedraft()
	{
		$content = trim(Yii::app()->request->getParam('content'));
		if($content)
		{
			Yii::app()->cache->set('edit_article_temp', $content,60*60);
		}
		echo 'success';
	}

	/**
	 * 删除文章
	 */
	public function actionDelete()
	{
		$id = intval(Yii::app()->request->getParam('id'));
		if(!$id)
		{
			$this->alert_error('ID不能为空');
		}

		//是否存在
		$CDbCriteria = new CDbCriteria;
		$CDbCriteria->condition = "id = '{$id}'";
		$article = Article::model()->find($CDbCriteria);
		if(!$article)
		{
			$this->alert_error('文章不存在。');
		}
		Article_recycle::backup($article);
		if($article->delete())
		{
			// 删除tag/category relations
			Article_category_relation::model()->deleteAll('article_id='.$id);
			$tag_rels = Article_tag_relation::model()->findAll('article_id='.$id);
			foreach ($tag_rels as $t)
			{
				$t->tag->used_times --;
				$t->tag->save();
				$t->delete();
			}
			$this->alert_ok();
		}
		else
		{
			$this->alert_error();
		}
	}
	/**
	 * 文章分类列表
	 */
	public function actionCategory()
	{
		$page = intval(Yii::app()->request->getParam('pageNum') - 1);

		$CDbCriteria = new CDbCriteria;

		$count = Article_category::model()->count();
		$pages = new CPagination($count);
		$pages->pageSize = self::PAGE_SIZE;
		$pages->currentPage = $page;
		$pages->applyLimit($CDbCriteria);

		$rows = Article_category::model()->findAll();

		$data = array();
		$data['rows'] = $rows;
		$data['pages'] = $pages;
		$this->display('category', $data);
	}

	/**
	 * 添加文章分类
	 */
	public function actionCategory_add()
	{
		$name = Yii::app()->request->getParam('name');
		$model_type = Yii::app()->request->getParam('model_type');

		//如果提交内容
		if($name)
		{
			$category = new Article_category();
			$category->name = $name;
			$category->model_type = $model_type;
			if($category->save())
			{
				$this->alert_ok();
			}
			else
			{
				$this->alert_error();
			}
		}
		else
		{
			$this->display('category_add');
		}
	}

	/**
	 * 修改文章分类
	 */
	public function actionCategory_edit()
	{
		$id = intval(Yii::app()->request->getParam('id'));
		$name = Yii::app()->request->getParam('name');
		$model_type = Yii::app()->request->getParam('model_type');
		if(!$id)
		{
			$this->alert_error('ID不能为空');
		}

		$CDbCriteria = new CDbCriteria;
		$CDbCriteria->condition = "id = '{$id}'";
		$category = Article_category::model()->find($CDbCriteria);
		if(!$category)
		{
			$this->alert_error('分类不存在');
		}

		//如果提交内容
		if($name)
		{
			$category->name = $name;
			$category->model_type = $model_type;
			if($category->save())
			{
				$this->alert_ok();
			}
			else
			{
				$this->alert_error();
			}
		}
		else
		{
			$data = array();
			$data['category'] = $category;
			$this->display('category_edit', $data);
		}
	}

	/**
	 * 删除分类
	 */
	public function actionCategory_delete()
	{
		$id = intval(Yii::app()->request->getParam('id'));
		if(!$id)
		{
			$this->alert_error('ID不能为空');
		}
		$category = Article_category::model()->findByPk($id);
		if(!$category)
		{
			$this->alert_error('分类不存在。');
		}

		if($category->delete())
		{
			Article_category_relation::model()->deleteAll('category_id='.$id);
			$this->alert_ok();
		}
		else
		{
			$this->alert_error();
		}
	}

	public function actionRecommend()
	{
		$id = intval(Yii::app()->request->getParam('id'));
		if(!$id)
		{
			$this->alert_error('ID不能为空');
		}

		$article = Article::model()->findByPk($id);
		if(!$article)
		{
			$this->alert_error('文章不存在。');
		}

		$article->is_recommend = 1;
		if($article->save())
		{
			$this->alert_ok();
		}
		else
		{
			$this->alert_error();
		}
	}

	public function actionUnrecommend()
	{
		$id = intval(Yii::app()->request->getParam('id'));
		if(!$id)
		{
			$this->alert_error('ID不能为空');
		}

		//是否存在
		$CDbCriteria = new CDbCriteria;
		$CDbCriteria->condition = "id = '{$id}'";
		$article = Article::model()->findByPk($id);
		if(!$article)
		{
			$this->alert_error('文章不存在。');
		}

		$article->is_recommend = 0;
		if($article->save())
		{
			$this->alert_ok();
		}
		else
		{
			$this->alert_error();
		}
	}
	
	public function actionUploadimg()
	{
		$inputName='filedata';//表单文件域name
		$baseDir= dirname(ROOT).'/img';//上传文件保存路径，结尾不要带/
		$maxAttachSize=20971520;//最大上传大小，默认是20M
		$upExt='jpg,jpeg,gif,png';//上传扩展名
		$baseURL = 'http://ixuepin.qiniudn.com';
		$msg = "";
		$tempPath=$baseDir.'/'.date("YmdHis").mt_rand(10000,99999).'.tmp';
		$localName='';
		
		if(isset($_SERVER['HTTP_CONTENT_DISPOSITION'])&&preg_match('/attachment;\s+name="(.+?)";\s+filename="(.+?)"/i',$_SERVER['HTTP_CONTENT_DISPOSITION'],$info)){//HTML5上传
			file_put_contents($tempPath,file_get_contents("php://input"));
			$localName=urldecode($info[2]);
		}
		else{//标准表单式上传
			$upfile=@$_FILES[$inputName];
			if(!isset($upfile)) $this->uploadend('文件域的name错误');
			elseif(!empty($upfile['error'])){
				switch($upfile['error'])
				{
					case '1':
						$this->uploadend('文件大小超过了php.ini定义的upload_max_filesize值');
						break;
					case '2':
						$this->uploadend('文件大小超过了HTML定义的MAX_FILE_SIZE值');
						break;
					case '3':
						$this->uploadend('文件上传不完全');
						break;
					case '4':
						$this->uploadend('无文件上传');
						break;
					case '6':
						$this->uploadend('缺少临时文件夹');
						break;
					case '7':
						$this->uploadend('写文件失败');
						break;
					case '8':
						$this->uploadend('上传被其它扩展中断');
						break;
					case '999':
					default:
						$this->uploadend('无有效错误代码');
				}
			}
			elseif(empty($upfile['tmp_name']) || $upfile['tmp_name'] == 'none')$this->uploadend('无文件上传');
			else{
				move_uploaded_file($upfile['tmp_name'],$tempPath);
				$localName=$upfile['name'];
			}
		}
		$fileInfo=pathinfo($localName);
		$extension=$fileInfo['extension'];
		if(preg_match('/'.str_replace(',','|',$upExt).'/i',$extension))
		{
			$bytes=filesize($tempPath);
			if($bytes > $maxAttachSize) $this->uploadend('请不要上传大小超过'.formatBytes($maxAttachSize).'的文件');
			$attachDir = $baseDir.'/day_'.date('ymd');
			if(!is_dir($attachDir))
			{
				@mkdir($attachDir, 0777);
				@fclose(fopen($attachDir.'/index.htm', 'w'));
			}
			$newFilename=date("His").str_replace(' ', '', $localName);
			$targetPath = $attachDir.'/'.$newFilename;
			
			rename($tempPath,$targetPath);
			@chmod($targetPath,0644);
			$msg = str_replace($baseDir, $baseURL, $targetPath);
		}
		else $this->uploadend('上传文件扩展名必需为：'.$upExt);
		
		@unlink($tempPath);
		$this->uploadend('',$msg);
	}
	
	private function uploadend($err,$msg='')
	{
		die(json_encode(array('err'=>$err,'msg'=>$msg)));
	}
	
	private function addtag($article_id,$tag,$kind=1)
	{
		$cond = new CDbCriteria();
		$cond->condition = 'tag=:tag';
		$cond->params = array(':tag'=>$tag);
		$tag_record = Tag::model()->find($cond);
		if(!$tag_record)
		{
			$tag_record = new Tag();
			$tag_record->tag = $tag;
			$tag_record->used_times = 0;
			$tag_record->save();
		}
		$relation = Article_tag_relation::model()->find("article_id=$article_id and tag_id={$tag_record->id}");
		if(!$relation)
		{
			$relation = new Article_tag_relation();
			$relation->article_id = $article_id;
			$relation->tag_id = $tag_record->id;
			$relation->save();
			$tag_record->used_times ++;
			$tag_record->save();
		}
	}
}

function hashimg($path)
{
	return substr(md5('Z6$3S@@!'.$path.'sd###2'),6,30);
}